//
//  ViewController.m
//  3.11、UIScrollView控件实现图片轮播
//
//  Created by 李坤 on 16/12/8.
//
//

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@property(nonatomic,strong)NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //图片宽度
    CGFloat imageW = self.scrollview.frame.size.width;
    //图片高
    CGFloat imageH = self.scrollview.frame.size.height;
    //图片的y
    CGFloat imageY = 0;
    //图片中数
    NSInteger totalCount = 5;
    //1.添加5涨图片
    for (int i = 0; i < totalCount; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        //图片x
        CGFloat imageX = i *imageW;
        //设置frame
        imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
        //设置图片
        NSString *name = [NSString stringWithFormat:@"img_0%d",i+1];
        imageView.image = [UIImage imageNamed:name];
        //隐藏指示条
        self.scrollview.showsHorizontalScrollIndicator = NO;
        [self.scrollview addSubview:imageView];
    }
    //2.设置scrollview的滚动范围
    CGFloat contentW = totalCount * imageW;
    //不允许在垂直方向上进行滚动
    self.scrollview.contentSize = CGSizeMake(contentW, 0);
    //3.设置分页
    self.scrollview.pagingEnabled = YES;
    //4.坚挺scrollview的滚动
    self.scrollview.delegate = self;
    self.pageControl.numberOfPages = 5;
    [self addTimer];
}

- (void)nextImage:(NSTimer *)obj{
    
//    NSLog(@"obj = %i",obj.userInfo == self.timer.userInfo);
    int page = (int)self.pageControl.currentPage;
    
    if(page == 4){
        page = 0;
    }else{
        page++;
    }
    //滚动scrollview
    CGFloat x = page * self.scrollview.frame.size.width;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    self.scrollview.contentOffset = CGPointMake(x, 0);
    [UIView commitAnimations];
}

//scrollview滚动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"滚动中");
    //计算页码
    CGFloat scrollviewW = scrollView.frame.size.width;
    CGFloat x = scrollView.contentOffset.x;
    int page = (x + scrollviewW/2)/scrollviewW;
    self.pageControl.currentPage = page;
}

// 开始拖拽的时候调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    NSLog(@"%s",__func__);
    //关闭定时器(注意点：定时器一旦关闭，无法再重启）
    [self removeTimer];
    
}

//拖拽结束调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"%s",__func__);
    //开启定时器
    [self addTimer];
    
}

/**
 *  开启定时器
 */
- (void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextImage:) userInfo:@"xxx" repeats:YES];
}

/**
 *  关闭定时器
 */
- (void)removeTimer{
    [self.timer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
